<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联竞赛id" prop="competitionId">
        <el-input
          v-model="queryParams.competitionId"
          placeholder="请输入关联竞赛id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="竞赛名称" prop="competitionName">
        <el-input
          v-model="queryParams.competitionName"
          placeholder="请输入竞赛名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生学号" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学生学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖项层次" prop="awardLevel">
        <el-select v-model="queryParams.awardLevel" placeholder="请选择奖项层次" clearable>
          <el-option
            v-for="item in awardLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖项等级" prop="awardGrade">
        <el-select v-model="queryParams.awardGrade" placeholder="请选择奖项等级" clearable>
          <el-option
            v-for="item in awardGradeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="获奖时间" prop="gainTime" style="width: 200px">
        <el-date-picker
          clearable
          v-model="queryParams.gainTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择获奖时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="审核状态" prop="reviewStatus">
        <el-select v-model="queryParams.reviewStatus" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="item in reviewStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:award:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:award:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:award:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:award:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="awardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="唯一标识ID" align="center" prop="id" />
      <el-table-column label="关联竞赛id" align="center" prop="competitionId" />
      <el-table-column label="竞赛名称" align="center" prop="competitionName" />
      <el-table-column label="学生姓名" align="center" prop="createBy"  />
      <el-table-column label="学生学号" align="center" prop="studentId" />
      <el-table-column label="奖项层次" align="center" prop="awardLevel" :formatter="formatAwardLevel" />
      <el-table-column label="奖项等级" align="center" prop="awardGrade" :formatter="formatAwardGrade" />
      <el-table-column label="证书图片" align="center" prop="certificateImg">
        <template #default="scope">
          <el-image 
            v-if="scope.row.certificateImg"
            style="width: 50px; height: 50px"
            :src="scope.row.certificateImg" 
            :preview-src-list="[scope.row.certificateImg]"
            fit="cover"
            preview-teleported
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="分值" align="center" prop="score" />
      <el-table-column label="获奖时间" align="center" prop="gainTime" :formatter="formatDate" />
      <el-table-column label="审核状态" align="center" prop="reviewStatus" :formatter="formatReviewStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:award:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:award:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改竞赛证书认证对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="awardRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联竞赛id" prop="competitionId">
          <el-input v-model="form.competitionId" placeholder="请输入关联竞赛id" />
        </el-form-item>
        <el-form-item label="竞赛名称" prop="competitionName">
          <el-input v-model="form.competitionName" placeholder="请输入竞赛名称" />
        </el-form-item>
        <el-form-item label="学生学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生学号" />
        </el-form-item>
        <el-form-item label="奖项层次" prop="awardLevel">
          <el-select v-model="form.awardLevel" placeholder="请选择奖项层次">
            <el-option
              v-for="item in awardLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="奖项等级" prop="awardGrade">
          <el-select v-model="form.awardGrade" placeholder="请选择奖项等级">
            <el-option
              v-for="item in awardGradeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input v-model="form.score" placeholder="请输入分值"  />
        </el-form-item>
        <el-form-item label="获奖时间" prop="gainTime">
          <el-date-picker
            clearable
            v-model="form.gainTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择获奖时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-select v-model="form.reviewStatus" placeholder="请选择审核状态">
            <el-option
              v-for="item in reviewStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Award">
import { listAward, getAward, delAward, addAward, updateAward } from "@/api/competitionmanagement/award";
import { listStudent, getStudent } from "@/api/infomanagement/student";
import { addLog, listLog, getLog, updateLog } from "@/api/analyzemanagement/log";

const { proxy } = getCurrentInstance();

const awardList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    competitionId: null,
    competitionName: null,
    studentId: null,
    awardLevel: null,
    awardGrade: null,
    certificateImg: null,
    reviewStatus: null,
    score: null,
    gainTime: null

  },
  rules: {
    competitionId: [
      { required: true, message: "关联竞赛id不能为空", trigger: "blur" }
    ],
    studentId: [
      { required: true, message: "学生学号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 奖项层次选项
const awardLevelOptions = ref([
  { value: '0', label: '校级' },
  { value: '1', label: '市级' },
  { value: '2', label: '省部级' },
  { value: '3', label: '国家级' }
]);

// 奖项等级选项
const awardGradeOptions = ref([
  { value: '0', label: '一等奖' },
  { value: '1', label: '二等奖' },
  { value: '2', label: '三等奖' },
  { value: '3', label: '优秀奖' },
  { value: '4', label: '参与奖' }
]);

// 审核状态选项
const reviewStatusOptions = ref([
  { value: '0', label: '未通过' },
  { value: '1', label: '通过' },
  { value: '2', label: '待审核' }
]);

// 格式化日期
const formatDate = (row, column) => {
  if (!row.gainTime) return '';
  
  // 创建Date对象
  const date = new Date(row.gainTime);
  
  // 如果日期无效，返回空字符串
  if (isNaN(date.getTime())) return '';
  
  // 调整为东八区时间（UTC+8）
  const utc8Time = new Date(date.getTime() + (8 * 60 * 60 * 1000) + (date.getTimezoneOffset() * 60 * 1000));
  
  // 格式化为YYYY-MM-DD
  const year = utc8Time.getFullYear();
  const month = String(utc8Time.getMonth() + 1).padStart(2, '0');
  const day = String(utc8Time.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
};

// 格式化奖项层次
const formatAwardLevel = (row, column) => {
  const level = row.awardLevel;
  const option = awardLevelOptions.value.find(item => item.value === level?.toString());
  return option ? option.label : level;
};

// 格式化奖项等级
const formatAwardGrade = (row, column) => {
  const grade = row.awardGrade;
  const option = awardGradeOptions.value.find(item => item.value === grade?.toString());
  return option ? option.label : grade;
};

// 格式化审核状态
const formatReviewStatus = (row, column) => {
  const status = row.reviewStatus;
  const option = reviewStatusOptions.value.find(item => item.value === status?.toString());
  return option ? option.label : status;
};

// 学生信息映射表
const studentMap = ref({});

// 格式化学生姓名
const formatStudentName = (row, column) => {
  const stuCode = row.studentId; // 表格中的字段仍然是studentId
  if (!stuCode) return '';
  
  // 如果学生信息已存在映射表中，直接返回姓名
  if (studentMap.value[stuCode]) {
    return studentMap.value[stuCode].realname || '';
  }
  
  // 否则从服务器获取学生信息
  getStudentNameById(stuCode);
  
  // 返回空字符串，等待异步获取完成后的更新
  return '';
};

// 根据学号获取学生详细信息
const getStudentInfoByStuCode = async (stuCode) => {
  try {
    // 先从缓存中查找
    if (studentMap.value[stuCode]) {
      return studentMap.value[stuCode];
    }
    
    // 如果缓存中没有，则从数据库获取
    const res = await listStudent({ stu_code: stuCode, pageSize: 1 });
    if (res.rows && res.rows.length > 0) {
      const studentInfo = res.rows[0];
      // 将获取到的学生信息缓存起来
      studentMap.value[stuCode] = studentInfo;
      return studentInfo;
    }
    return null;
  } catch (error) {
    console.error('获取学生信息失败:', error);
    return null;
  }
};

// 根据学号获取学生姓名（使用合并后的方法）
const getStudentNameById = async (stuCode) => {
  const studentInfo = await getStudentInfoByStuCode(stuCode);
  return studentInfo ? studentInfo.realname : '';
};

/** 查询竞赛证书认证列表 */
function getList() {
  loading.value = true;
  listAward(queryParams.value).then(response => {
    awardList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    
    // 预加载学生姓名
    preloadStudentNames();
  });
}

// 预加载学生姓名
const preloadStudentNames = async () => {
  // 获取所有不重复的学号
  const uniqueStudentIds = [...new Set(awardList.value.map(item => item.studentId).filter(id => id))];
  
  // 批量获取学生姓名
  for (const stuCode of uniqueStudentIds) {
    if (!studentMap.value[stuCode]) {
      await getStudentNameById(stuCode);
    }
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    competitionId: null,
    competitionName: null,
    studentId: null,
    awardLevel: null,
    awardGrade: null,
    certificateImg: null,
    createBy: null,
    createTime: null,
    reviewStatus: null,
    score: null,
    gainTime: null
  };
  proxy.resetForm("awardRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加竞赛证书认证";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAward(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改竞赛证书认证";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["awardRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      if (form.value.id != null) {
        // 修改操作
        updateAward(form.value).then(async response => {
          // 检查审核状态是否从非1改为1
          // 先获取原始数据
          const originalAward = awardList.value.find(item => item.id === form.value.id);
          const isReviewStatusChangedToApproved = originalAward && 
            originalAward.reviewStatus !== '1' && form.value.reviewStatus === '1';
          
          if (isReviewStatusChangedToApproved) {
            // 审核状态改为通过，添加日志记录
            await addLogRecord(form.value);
          }
          
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => { proxy.$modal.closeLoading(); });
      } else {
        // 新增操作
        addAward(form.value).then(response => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => { proxy.$modal.closeLoading(); });
      }
    }
  });
}

// 检查log记录是否已存在
const checkLogExists = async (recordId) => {
  try {
    const res = await listLog({ logType: 2, recordId: recordId });
    if (res.rows && res.rows.length > 0) {
      return { exists: true, logData: res.rows[0] };
    }
    return { exists: false, logData: null };
  } catch (error) {
    console.error('检查log记录失败:', error);
    return { exists: false, logData: null };
  }
};

// 添加日志记录
const addLogRecord = async (awardData) => {
  try {
    // 获取学生详细信息（使用合并后的方法）
    const studentInfo = await getStudentInfoByStuCode(awardData.studentId);
    if (!studentInfo) {
      console.error('无法获取学生信息');
      return;
    }
    
    // 获取奖项层次和等级的标签
    const awardLevelLabel = awardLevelOptions.value.find(item => item.value === awardData.awardLevel?.toString())?.label || '';
    const awardGradeLabel = awardGradeOptions.value.find(item => item.value === awardData.awardGrade?.toString())?.label || '';
    
    // 构造日志内容
    const content = `${studentInfo.createBy}获得了${awardData.competitionName}${awardLevelLabel}${awardGradeLabel}分数${awardData.score}`;
    
    // 构造日志数据
    const logData = {
      logType: 2,  // 日志类型默认为2
      studentNumber: awardData.studentId,  // 学生学号
      studentName: awardData.createBy,  // 学生姓名
      score: awardData.score,  // 分值
      content: content,  // 内容
      direction: studentInfo.directionId,  // 方向ID
      recordId: awardData.id  // 记录ID
    };
    
    // 检查log记录是否已存在
    const { exists, logData: existingLog } = await checkLogExists(awardData.id);
    
    if (exists) {
      // 如果记录已存在，则进行全部字段的修改操作
      // 保留原有的ID，更新其他所有字段
      const updatedLogData = {
        ...logData,
        id: existingLog.id  // 保留原有的ID
      };
      await updateLog(updatedLogData);
    } else {
      // 如果记录不存在，则新增记录
      await addLog(logData);
    }
  } catch (error) {
    console.error('添加/更新日志记录失败:', error);
  }
};

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除竞赛证书认证编号为"' + _ids + '"的数据项？').then(function() {
    return delAward(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/award/export', {
    ...queryParams.value
  }, `award_${new Date().getTime()}.xlsx`)
}

getList();
</script>
